<script lang="ts" setup>
import { ref } from 'vue'
import { debounce } from 'lodash-es'
import TextBlink from '@/components/TextBlink/index.vue'
import Conference from '@/api/modules/conference'
import Speech from '@/utils/speech'

const route = useRoute()
const speech = new Speech()

const notFoundMessage = ref('加载中...')

// 滚动等待栏
const waitList = ref<HTMLDivElement | null>(null)
let lastTime = 0
let stopDuration = 0
let scrollDirection = 1
function scrollAnimation(now: number) {
  const delta = now - lastTime
  const offset = delta / 20
  lastTime = now
  if (waitList.value && waitList.value.scrollHeight > waitList.value.clientHeight + 23) {
    // 滚动到顶部或底部时停顿3秒
    if (waitList.value.scrollTop === 0 || waitList.value.scrollTop >= waitList.value.scrollHeight - waitList.value.clientHeight - 1) {
      stopDuration += delta
      if (stopDuration >= 3000) {
        scrollDirection = -scrollDirection
        waitList.value.scrollTop += delta * scrollDirection
        stopDuration = 0
      }
    }
    // 滚动中
    else {
      waitList.value.scrollTop += offset * scrollDirection
    }
  }
  requestAnimationFrame(scrollAnimation)
}

requestAnimationFrame(scrollAnimation)

const meeting = ref<MeetingApiTypes | null>(null)
// 当前进行中的会议信息
const currentSubject = ref<SubjectApiTypes.subjectItem | null>(null)
// 已完成的议题列表
const completedSubjectList = ref<SubjectApiTypes.subjectItem[]>([])
// 等待呼叫的议题列表
const waitingSubjectList = ref<SubjectApiTypes.subjectItem[]>([])

// 临时新增人员
const tempAddPerson = ref<SubjectApiTypes.Person[]>([])

// 筛选并更新议题列表
function updateSubjectList(clearTempAddPerson = true) {
  if (!meeting.value) {
    return
  }

  // 根据议题状态筛选
  completedSubjectList.value = meeting.value.subjectList.filter(subject => subject.status === 2)
  waitingSubjectList.value = meeting.value.subjectList.filter(subject => subject.status === 0)
  const currentSubjectIndex = meeting.value.subjectList.findIndex(subject => subject.status === 1)
  if (currentSubjectIndex !== -1) {
    currentSubject.value = meeting.value.subjectList[currentSubjectIndex]
  }
  else {
    currentSubject.value = null
  }

  if (clearTempAddPerson) {
    tempAddPerson.value = []
  }
}
updateSubjectList()

const repullMeeting = debounce(() => {
  Conference.getDetail(route.params.id as string).then((res) => {
    meeting.value = res.data
    updateSubjectList()
  })
}, 1000)

// websocket连接
const BASEURL = import.meta.env.VITE_APP_WS_BASEURL
let websocket: WebSocket | null = null
onMounted(() => {
  websocket = new WebSocket(`${BASEURL}${route.params.id}`)
  websocket.onmessage = (event) => {
    const msg = JSON.parse(event.data)
    if (msg.type === 'repullMeeting') { // 重新拉取会议信息
      repullMeeting()
    }
    else if (msg.type === 'addTempPersons') { // 临时新增人员
      const subjectId = msg.data.subjectId// 议题id
      const tempPersons = msg.data.tempPersons// 临时新增人员列表
      const subject = meeting.value?.subjectList.find(subject => subject.id === subjectId)
      if (subject) { // 会议中存在该议题
        subject.personList.push(...tempPersons)
      }
      if (currentSubject.value?.id === subjectId) { // 如果是当前进行中的议题，则新增人员还需显示到新增列席处
        tempAddPerson.value.push(...tempPersons)
        // 播报人员信息
        let personMsg = '请'
        for (const person of tempPersons) {
          personMsg += `${person.name}，`
        }
        personMsg += '马上参会'
        speech.speak(personMsg)
      }
    }
    else if (msg.type === 'noSuchMeeting') { // 会议不存在
      meeting.value = null
    }
    else if (msg.type === 'meetingInfo') { // 会议信息
      meeting.value = msg.data
      updateSubjectList()
      speech.speak('语音测试')
    }
    else if (msg.type === 'updateSubjectStatus') { // 开始议题
      const { subjectId, status } = msg.data
      const subject = meeting.value?.subjectList.find(subject => subject.id === subjectId)
      if (subject) {
        subject.status = status
      }
      updateSubjectList()
      if (status === 1) {
        // 播报议题信息
        const index = meeting.value?.subjectList.findIndex(subject => subject.id === subjectId)
        if (index === -1) {
          console.error('议题不存在')
        }
        speech.speak(`请第${index! + 1}项议题的相关人员参会`)
      }
    }
    else if (msg.type === 'addSubject') { // 新增议题
      const subject = msg.data
      meeting.value?.subjectList.push(subject)
      updateSubjectList(false)
    }
    else if (msg.type === 'removeSubject') { // 移除议题
      const subjectId = msg.data
      const subjectIndex = meeting.value?.subjectList.findIndex(subject => subject.id === subjectId)
      if (subjectIndex !== undefined && subjectIndex !== -1) {
        meeting.value?.subjectList.splice(subjectIndex, 1)
      }
      updateSubjectList(false)
    }

    notFoundMessage.value = '找不到该会议信息'
  }
})
onUnmounted(() => {
  websocket?.close()
})
</script>

<template>
  <div class="sub-conference">
    <div v-if="meeting">
      <header>
        <h2>{{ meeting.name }}</h2>
      </header>
      <div class="container border">
        <main>
          <div class="left border-bottom border-right">
            <h3 class="border-bottom">
              正在进行
            </h3>
            <div class="meeting-name">
              {{ currentSubject?.name }}
            </div>
            <h3 class="border-top border-bottom">
              列席人员
            </h3>
            <div class="person-list">
              <div v-for="person in currentSubject?.personList" :key="person.id" class="item">
                <TextBlink>
                  {{ person.name }}
                </TextBlink>
              </div>
            </div>
          </div>
          <div class="right border-bottom">
            <h3 class="border-bottom">
              等待呼叫
            </h3>
            <div ref="waitList" class="wait-list">
              <div v-for="(subject) in waitingSubjectList" :key="subject.id" class="item meeting-name">
                {{ subject.name }}
              </div>
              <div class="bottom-gap">
                到底了
              </div>
            </div>
          </div>
        </main>
        <footer>
          <div class="left border-right">
            <span>新增列席</span>
          </div>
          <div class="content">
            <TextBlink v-for="person in tempAddPerson" :key="person.id">
              {{ `${person.name} ` }}
            </TextBlink>
          </div>
        </footer>
      </div>
    </div>
    <div v-else class="text-notfound">
      {{ notFoundMessage }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.border {
  border: 1px solid black;
}

.border-top {
  border-top: 1px solid black;
}

.border-left {
  border-left: 1px solid black;
}

.border-bottom {
  border-bottom: 1px solid black;
}

.border-right {
  border-right: 1px solid black;
}

.scroll-text {
  font-size: 30px;
  color: red;
}

header {
  text-align: center;

  h2 {
    font-size: 40px;
    color: red;
    font-weight: 400;
    margin: 0;
    padding: 20px 0;
  }
}

.container {
  width: 80%;
  margin: 0 auto;

  .meeting-name {
    font-size: 20px;
    padding: 14px;
  }

  main {
    display: flex;

    h3 {
      text-align: center;
      background-color: #00b0f0;
      margin: 0;
      padding: 20px 0;
      font-size: 21px;
    }

    .left {
      flex-basis: 40%;
      width: 40%;

      .person-list {
        padding: 20px;
        display: flex;
        flex-wrap: wrap;
        gap: 20px;

        .item {
          font-size: 18px;
        }
      }
    }

    .right {
      flex-basis: 60%;
      width: 60%;

      .wait-list {
        height: 329px; /* 6个议题的高度 - 1px */
        overflow: hidden;

        .item {
          border-bottom: 1px solid black;
        }

        .bottom-gap {
          height: 20px;
          line-height: 20px;
          font-size: 12px;
          color: #aaa;
          text-align: center;
        }
      }
    }
  }

  footer {
    display: flex;
    height: 100px;

    .left {
      padding: 0 20px;
      width: 200px;
      font-size: 18px;
      display: flex;
      align-items: center;
    }

    .content {
      padding: 20px;
      font-size: 18px;
    }
  }
}

.text-notfound {
  text-align: center;
  color: red;
  font-size: 40px;
}
</style>
